import { message } from "antd"
import axios, { AxiosRequestConfig, AxiosError, AxiosResponse } from "axios"
import { createHashHistory } from "history"

axios.defaults.baseURL = "http://49.235.112.159:7763"
// axios.defaults.withCredentials = true

const history = createHashHistory()

axios.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = sessionStorage.getItem("token")
    if (token !== null) config.headers = { ...config.headers, Authorization: token }
    return config
  },
  (err: AxiosError) => Promise.reject(err)
)

axios.interceptors.response.use(
  (res: AxiosResponse) => {
    return res
  },
  (err: AxiosError) => {
    if (err.response?.status === 401) {
      sessionStorage.removeItem("token")
      message.error("token过期或无效")
      setTimeout(() => {
        history.replace("/login")
      }, 2000)
    }
    Promise.reject(err)
  }
)

export const http = axios
